package dao.jdo;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.inject.Inject;

import dao.GenericDAO;

public abstract class GenericDAOImpl<E, Id extends Serializable> implements GenericDAO<E, Id> {
	
	private PersistenceManager pm;
	private Class<E> entityClass = null;
	
	@SuppressWarnings("unchecked")
	@Override
	public Class<E> getEntityClass() {
		if(entityClass == null) {
			ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
			entityClass = (Class<E>) type.getActualTypeArguments()[0];
		}
		return entityClass;
	}
	
	@Override
	public E save(E entity) {
		return pm.makePersistent(entity);
	}
	
	@Override
	public void delete(E entity) {
		pm.deletePersistent(entity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> getAll() {
		Query query = pm.newQuery(getEntityClass());
		return (List<E>) query.execute();
	}

	@Override
	public E getById(Id id) {
		return (E) pm.getObjectById(getEntityClass(), id);
	}

	public PersistenceManager getPersistenceManager() {
		return pm;
	}
	
	@Inject
	public void setPersistenceManager(PersistenceManager persistenceManager) {
		this.pm = persistenceManager;
	}
	
}
